package com.computercourse.order.mq;

import com.computercourse.framework.domain.task.CicTask;
import com.computercourse.order.config.RabbitMQConfig;
import com.computercourse.order.service.TaskService;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @description:
 * @author: yuanfeng
 * @date: Created in 2020/2/14 9:58 下午
 * @version: 1.0
 */
@Component
public class ChooseCourseTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(ChooseCourseTask.class);

    @Autowired
    private TaskService taskService;

    //每隔1分钟扫描消息表，向mq发送消息
    @Scheduled(fixedDelay = 60000)
    public void sendChooseCourseTask() {

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.set(GregorianCalendar.MINUTE, -1);
        Date time = calendar.getTime();
        List<CicTask> cicTaskList = taskService.findTaskList(time, 100);

        //遍历任务列表
        for (CicTask cicTask : cicTaskList) {
            //调用乐观锁方法校验任务是否可以执行
            if (taskService.getTask(cicTask.getId(), cicTask.getVersion()) > 0) {
                //发送选课消息
                taskService.publish(cicTask, cicTask.getMqExchange(), cicTask.getMqRoutingkey());
                LOGGER.info("send choose course task id:{}", cicTask.getId());

            }
        }

    }


    /**
     * 接收选课响应结果
     */
    @RabbitListener(queues = {RabbitMQConfig.CIC_LEARNING_FINISHADDCHOOSECOURSE})
    public void receiveFinishChooseCourseTask(CicTask cicTask, Message message, Channel channel) throws IOException {

        LOGGER.info("receiveChoosecourseTask...{}", cicTask.getId());
        if (Objects.nonNull(cicTask) && StringUtils.isNotEmpty(cicTask.getId())) {
            taskService.finishTask(cicTask.getId());
        }


    }
}